import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Form, Dialog, NumberPicker } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { column } from '../stores/definitions_refund';
import { observer } from 'mobx-react-lite';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import { observable } from 'mobx';

const FromItem = Form.Item;
const tableId = uniqueId('tauTable-');

const SupplementPay = ({ order, modal, onSubmit, onCancel }) => {
  const { ccOrderStore: store } = useStore();
  const [supplement] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [account, setAccount] = useState([]);
  const paramsRef = useRef(null);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const res = await store.get(order?.id);
      const payee = await getOrderPayee(res);
      paramsRef.current = { payee };
      await getAccount(res);
      editCtx.origin = _.cloneDeep(order);
      _.assign(supplement, res);
    })();
  }, [order]);

  if (!order) return <></>;

  async function getOrderPayee(args) {
    const _args = _.cloneDeep(args);
    const { id } = _args;
    const res = await store.getOrderPayee({ outTradeNo: id, subOutTradeNo: `${id}` });
    return res;
  }

  async function getAccount(args) {
    const _args = _.cloneDeep(args);
    const { id, ccOrder } = _args;
    const { directRoute } = ccOrder;
    let currentCompany = true;
    const res = await store.getAccount(id, directRoute);
    for (let i = 0; i < res.length; i++) {
      const e = res[i];
      if ((e.targetId === 'PLATFORM') || (e.tableId === 'CN1079')) {
        currentCompany = false;
      }
    }
    if (currentCompany) {
      const _supplement = [...res, { targetName: t`平台`, targetId: 'PLATFORM', targetType: 'PLATFORM', pendingSettlementAmount: 0, contributionAmount: 0 }];
      setAccount(_supplement);
      return;
    }
    setAccount(res);
  }

  const handleOnChange = (__, r) => {
    const { name, value } = r;
    _.set(supplement, name, value);
  };

  function handleChangeAccount(result) {
    const cloneResult = _.cloneDeep(result);
    paramsRef.current = {
      ...paramsRef.current,
      resultAccount: result,
    };
    setAccount(result);
    const totalAmount = cloneResult.reduce((acc, arr) => {
      const { amount = 0 } = arr;
      acc += amount;
      return acc;
    }, 0);
    _.set(supplement, 'amount', totalAmount);
  }

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const result = store.transferSupplementParams(supplement, paramsRef.current);
    onSubmit?.(result);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={supplement}
      useLabelForErrorMessage
      onCancel={handleCancel}
      onChange={handleOnChange}
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={supplement}
        mode={'view'}
        fields={['orderNumber', 'price', 'beginAreaName', 'endAreaName']}
      />
      <TitleGrid title={t`支付信息`} />
      <FieldsGrid
        formData={supplement}
        mode={'view'}
        fields={['amount']}
      />
      <TitleGrid title={t`分账方信息`} />
      <Account account={account} getAccount={(r) => handleChangeAccount(r)} />
      <TitleGrid title={t`备注信息`} />
      <FieldsGrid
        formData={supplement}
        mode={'edit'}
        fields={['reason']}
      />
      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

const Account = observer(({ account, getAccount }) => {
  const { ccOrderStore: store } = useStore();
  const [initAccount, setInitAccount] = useState([]);


  useEffect(() => {
    if (account.length > 0) {
      setInitAccount(account);
    }
  }, [account]);

  /**
   * 分账方输入分账金额事件
   * @param {*} e
   * @param {*} r
   * @param {*} i
   */
  const handleAccountPrice = (v, r, i) => {
    const tempAccount = _.cloneDeep(account);
    tempAccount[i].amount = v;
    setInitAccount(tempAccount);
    getAccount?.(tempAccount);
  };

  return (
    <TauTable
      instanceId={tableId}
      tableLayout="fixed"
      hidePagination
      style={{ width: '100%' }}
      dataSource={initAccount}
      rowKey="account" // 设置每行的唯一标识
      columns={[
        { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.ticIdx(i) },
        column('targetName', {
          width: 100,
          cell: (v, i, r) => {
            const { targetName, targetId } = r;
            return (
              <>
                <div>{targetName}</div>
                <div style={{ color: '#999' }}>{targetId}</div>
              </>
            );
          },
        }),
        {
          dataIndex: 'amount',
          title: t`分配金额`,
          width: 100,
          cell: (v, i, r) => {
            return <NumberPicker value={v} precision={2} style={{ width: 120 }} min={0} onChange={(e) => handleAccountPrice(e, r, i)} />
          },
        },
      ]}
    />
  );
});


export default observer(SupplementPay);

